/*
 * Copyright (c) 2020, 2023, 3044483124@qq.com All rights reserved.
 *
 */
package cn.Fibonacci;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * <p>Project: JavaStudy - ForkJoinDemo
 * <p>Powered by jiangbo On 2023-01-31
 * 10:29:26
 * <p>Created by IntelliJ IDEA
 *
 * @author jiangbo [3044483124@qq.com]
 * @version 1.0
 * @since 8/17
 */
public class ForkJoinDemo {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        ForkJoinPool pool = new ForkJoinPool();
        SumRecursiveTask1 task = new SumRecursiveTask1(1, 500000);
        Long result = pool.invoke(task);
        System.out.println("result = " + result);
        long end = System.currentTimeMillis();
        System.out.println("消耗的时间为: " + (end - start));
        System.out.println("-----------------------------------");
        long ok = 0;
        for (int i = 1; i <= 500000; i++) {
            ok += i;
        }
        System.out.println("result = " + ok);
        end = System.currentTimeMillis();
        System.out.println("消耗的时间为: " + (end - start));
    }
}
/*sum 求各 Recursive 递归循环 task 工作任务*/
class SumRecursiveTask1 extends RecursiveTask<Long> {
    private static final long THRESHOLD = 3000L;
    private final long start;
    private final long end;
    private long num = 0L;
    public SumRecursiveTask1(long start, long end) {
        this.start = start;
        this.end = end;
    }
    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= THRESHOLD) {
// 任务不用再拆分了.可以计算了
            long sum = 0;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            System.out.println("计算: " + start + " -> " + end + ",结果为: " + sum);
            return sum;
        } else {
// 数量大于预定的数量,任务还需要再拆分
            long middle = (start + end) / 2;
            System.out.println("拆分: 左边 " + start + " -> " + middle + ", 右边 " + (middle + 1) + " -> " + end);
            SumRecursiveTask1 left = new SumRecursiveTask1(start, middle);
            left.fork();
            SumRecursiveTask1 right = new SumRecursiveTask1(middle + 1,end);
            right.fork();
            return left.join() + right.join();
        }
    }

}


